<?php
class WallController extends MainController implements ControllerInterface {

	private $_lastEntry = '567w89oedijfh';

	public function preDispatch($param) {
		$this->Run($param);
	}

	public function postDispatch($param) {
		if($param['methodToRun'] == 'Upload')
			return;

		// nagłówek strony
		$this->RunShared('Header', $param);


		// footer
		$this->RunShared('Footer', $param);
	}

	public function IndexAction($param) {
		$this->addDescription($this->t('meta_description_wallIndex'));
		$this->addKeywords($this->t('meta_keywords_wallIndex'));
		$this->addTitle($this->t('Discussion wall'));		
		if(!$this->userLoggedIn) {
			return $this->addRedirectInfo($this->t('To take part in any dicussion first you must log in.'),'info',Router::Generateurl('default'));
		}		

		
		$this->runShared('CategoriesAndBrands');
		$this->runShared('Wall',array('userLoggedIn' => $this->userLoggedIn));
		$this->runShared('UserInfo',array('userId' => $this->user->getId()));
		
		$this->addDescription($this->t('meta_description_wallIndex'));
		$this->addKeywords($this->t('meta_keywords_wallIndex'));
		$this->addTitle($this->t('Discussion wall'));
		$this->addBreadCrumb('Discussion wall',Router::GenerateUrl('wallIndex'));
                
                //galerie
			
		$dalData = UserGalleryDAL::GetDalDataObj();
		$dalData->addCondition('user_gallery.active', '1');
		$dalData->setOrderBy('date DESC');
		$dalData->setLimit('4');
		$dalData->addJoin('User', 'Join user ON user_gallery.id_user=user.id_user');
		$result = UserGalleryDAL::GetResult($dalData);
		$this->smarty->assign('userGallery', $result);


	}

	private function UpdateNewestDate($date) {
		if(SessionProxy::IsSetValue($this->_lastEntry)) {
			$_date = SessionProxy::GetValue($this->_lastEntry);
			if(strtotime($_date) > strtotime($date))
				return false;
			else{
				SessionProxy::SetValue($this->_lastEntry, $date);
				return true;
			}
		}else{
			SessionProxy::SetValue($this->_lastEntry, $date);
			return true;
		}
	}

	public function LoadWallAction($param) {
		if(!$this->userLoggedIn)return;
		header('Content-type: text/html; Charset=utf-8');
		$refresh = intval(Request::Check('refresh')?Request::GetGet('refresh'):0);

		if($refresh == 0 && SessionProxy::IsSetValue($this->_lastEntry))
				SessionProxy::ClearValue($this->_lastEntry);

		$wall_limit = Registry::Get('initial_wall_limit');
		$limit = ($wall_limit*$refresh).', '.($wall_limit + 1);

		

		$usersWallDAL = UsersWallDAL::GetDalDataObj();
		$usersWallDAL->addCondition('users_wall.id_parent',0);
		$usersWallDAL->addCondition('(users_wall.id_user',$this->user->getId(),'=');
		//tutaj na dole warunek do znajomych
		$usersWallDAL->addCondition('users_wall.id_user','(SELECT user_connections.id_user_target FROM user_connections WHERE user_connections.id_user = '.$this->user->getId().' )',' IN ',' OR ');
		$usersWallDAL->addCondition('users_wall.global_users','1)','=','OR');

		$usersWallDAL->setSortBy('date DESC');
		$usersWallDAL->setLimit($limit);
		$usersWallDAL->addSelectFields('commentCount','(SELECT COUNT(a.id_users_wall) FROM users_wall a WHERE a.id_parent = users_wall.id_users_wall)');

		$usersWallDAL->addJoin('User',' LEFT JOIN user ON(users_wall.id_user = user.id_user)');

		$list = UsersWallDAL::GetResult($usersWallDAL);
		if(count($list) < ($wall_limit + 1)) {
			$this->smarty->assign('preload',1);
			
		}else{
			array_pop($list);
		}


		if(count($list) > 1)foreach($list AS $item)
			$this->UpdateNewestDate($item->getDate());

		$this->smarty->assign('list',$list);

	}

	public function PostWallAction($param) {
		$this->partialTemplate = 'LoadWall.tpl';
		if(!$this->userLoggedIn)return;
		header('Content-type: text/html; Charset=utf-8');
		$curr_date = date('Y-m-d G:i:s',time());
		$date = SessionProxy::IsSetValue($this->_lastEntry)?SessionProxy::GetValue($this->_lastEntry):$curr_date;

		if(Request::IsPost() && Request::Check('msg') && strlen(Request::GetPost('msg')) > 0) {
			$uw = new UsersWall();
			$uw->setIdUser($this->user->getId());
			$msg = Request::GetPost('msg');

			$prepend = '';

			if(Request::Check('attachment_image')) {
				$prepend .= '<p>';

				if(is_array(Request::GetPost('attachment_image')))foreach(Request::GetPost('attachment_image') AS $src) {
					$prepend .= '<img class="wallImage" alt="wallImage" src="'.$src.'" /><br />';
				}

				$prepend .= '</p>';
			}

			$uw->setDescription("$prepend<p>$msg</p>");
			$uw->setDate(date('Y-m-d G:i:s',time()));
			$uw->setIdParent(Request::GetPost('parent')>0?Request::GetPost('parent'):0);
			if(Request::Check('expert') && intval(Request::GetPost('expert')) == 1) {
				$uw->setGlobalUsers(1);
			}

			UsersWallDAL::Save($uw->getDalDataObj());

			if($uw->getIdParent() > 0) {
				$this->RunShared('addActivityPoints', array(
				  'action' => 'USER_WALL_COMMENT',
				  'idUser' => $this->user->getId(),
				  'tpl_vars' => array()
				 ));
			}else{
				$this->RunShared('addActivityPoints', array(
				  'action' => 'USER_WALL_POST',
				  'idUser' => $this->user->getId(),
				  'tpl_vars' => array()
				 ));
			}
		}

		

		$usersWallDAL = UsersWallDAL::GetDalDataObj();
		
		if(Request::Check('parent') && Request::GetPost('parent') > 0) {
			$usersWallDAL->addCondition('users_wall.id_parent',Request::GetPost('parent'));
			$usersWallDAL->setSortBy('users_wall.date ASC');
			$this->smarty->assign('parent',Request::GetPost('parent'));
		}else{
			$usersWallDAL->addCondition('users_wall.date',"'$date'",$date==$curr_date?'>=':'>');
			$usersWallDAL->addCondition('(users_wall.id_user','(SELECT user_connections.id_user_target FROM user_connections WHERE user_connections.id_user = '.$this->user->getId().' )',' IN ');
			$usersWallDAL->addCondition('(users_wall.id_user',$this->user->getId().')','=',' OR ');
			$usersWallDAL->addCondition('users_wall.global_users','1)','=','OR');
			$usersWallDAL->addCondition('users_wall.id_parent',0);
			
			$usersWallDAL->setSortBy('users_wall.date DESC');
			
			
		}
		//tutaj na dole warunek do znajomych
		//$usersWallDAl->addCondition('id_user','(SELECT )',' IN ',' OR ');
		
		$usersWallDAL->addSelectFields('commentCount','(SELECT COUNT(a.id_users_wall) FROM users_wall a WHERE a.id_parent = users_wall.id_users_wall)');


		$usersWallDAL->addJoin('User',' LEFT JOIN user ON(users_wall.id_user = user.id_user)');

		$list = UsersWallDAL::GetResult($usersWallDAL);

		if(count($list) > 1)foreach($list AS $item)
			$this->UpdateNewestDate($item->getDate());

		$this->smarty->assign('list',$list);

		$this->smarty->assign('preload',true);

		
	}

	public function UploadAction($param) {
		$this->setAjaxRender();
		$this->smarty->assign('uploaded',false);

		if(isset($_FILES['attachment']) && is_uploaded_file($_FILES['attachment']['tmp_name'])) {
			$images = array('jpg','png','gif');
			$ext = strtolower(array_pop(explode('.',$_FILES['attachment']['name'])));

			if(in_array($ext, $images)) {
				$dir = PATH_STATIC_CONTENT . '/upload/wall';
				if(!is_dir($dir))
					mkdir($dir);

				$filename = md5(microtime()).'.'.$ext;

				if(move_uploaded_file($_FILES['attachment']['tmp_name'], $dir.'/'.$filename)) {
					$this->smarty->assign('type','image');
					$this->smarty->assign('src','upload/wall/'.$filename);
					$this->smarty->assign('uploaded',true);
				}
			}

		}
	}
}